package com.friends.utils.file;

import lombok.experimental.UtilityClass;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;

import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 文件读取并写出
 * @Author Z-7
 * @Date 2022/10/28
 */
@Slf4j
@UtilityClass
public class FileReadUtil {
    /**
     * 桌面地址
     */
    private static final String DESKTOP = "C:\\Users\\Admini\\Desktop\\";

    public static void main(String[] args) throws IOException {
        //List<String> strings = readFilesToList(new File("C:\\Users\\Admini\\Desktop\\售电量分析"));
        List<String> strings = readFilesToList(new File(DESKTOP + "sh_zhss.sql"));
        //       writeFile(strings,"D:\\sql.txt");
        writeFiles(strings,5000);
    }

    /**
     * 传入文件/文件夹 将所有文件内容存入list（仅限文字）
     * @param file
     * @return
     * @throws IOException
     */
    public static List<String> readFilesToList(File file) throws IOException {
        List<String> list = new ArrayList<>();
        File[] files = file.listFiles();
        // 存在文件
        if (ArrayUtils.isNotEmpty(files)) {
            for (File item : files) {
                // 递归至底层
                List<String> contextList = readFilesToList(item);
                // 添加至最后的集合中
                list.addAll(contextList);
            }
        }
        // 如果传入的是文件夹，直接返回 必须保留 不然会报错的
        if (file.isDirectory()) {
            return list;
        }
//        if (list.size() > 6500) {
//            return list;
//        }
//        if (!StringUtils.lowerCase(file.getName()).startsWith("home")) {
//            return list;
//        }
        // 读取文件存入list
        list = recursionRead(file);
        return list;
    }

    /**
     * 读取文件内容，存入list
     * @param file 具体文件对象（不能是文件夹）
     * @return
     * @throws IOException
     */
    public static List<String> recursionRead(File file) throws IOException {
        List<String> list = new ArrayList<>();
        // 读取文件 存入list
        BufferedReader br = new BufferedReader(new FileReader(file));
        String context;
        while (true) {
            boolean result = StringUtils.isNotBlank(context = br.readLine());
            if (!result) {
                String text;
                // 防止空行
                for (int i = 0; i < 5; i++) {
                    if (StringUtils.isNotBlank((text = br.readLine()))) {
                        context = text;
                        break;
                    } else if (i >= 4) {
                        log.info("文件：{}，读取完毕", file.getAbsolutePath());
                        return list;
                    } else {
                        log.info("第{}次尝试", i + 1);
                    }
                }

            }
            list.add(context);
        }
    }


    /**
     * 读取某个文件夹下的所有文件，并存入list
     *
     * @param path
     * @return
     * @throws IOException
     */
    public static List<String> readFile(String path) throws IOException {
        File file = new File(path);
        File[] files = file.listFiles();
        // 获取所有的文件名称
        List<String> names = Arrays.stream(files).filter(item -> !item.isDirectory()).map(a -> a.getName()).collect(Collectors.toList());
        List<String> list = new ArrayList<>();
        for (String name : names) {
            String fileName = path + "\\" + name;
            BufferedReader br = new BufferedReader(new FileReader(fileName));
            String context = null;
            while (StringUtils.isNotBlank((context = br.readLine()))) {
                list.add(context);
            }
            // 防止空行
            for (int i = 0; i < 5; i++) {
                if (StringUtils.isNotBlank((context = br.readLine()))) {
                    list.add(context);
                } else {
                    System.out.println("第" + i + "次尝试");
                }
            }
            br.close();
        }
        return list;
    }

    /**
     * 将list集合中的内容写出到文件
     * @param list
     * @param path
     */
    public static void writeFile(List<String> list, String path) {
        try {
            File file = new File(path);
            if (file.exists()) {
                // 文件存在
                file.delete();
                log.info("File " + file.getName() + " 存在，已删除！");
            }
            FileOutputStream fileOutputStream = new FileOutputStream(file, true);
            list.forEach(item -> {
                try {
                    fileOutputStream.write((item + "\r\n").getBytes());
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            });
            System.out.println("写入完成，文件地址：" + path);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * @param list 要写出的集合，后缀-0  -1 ...
     * @param step 每个文件多少行
     */
    public static void writeFiles(List<String> list, Integer step) {
        try {
            int size = 0;
            File file = new File("D:\\file\\output-" + size + ".txt");

//            FileWriter writer = new FileWriter(writeName);
//            BufferedWriter out = new BufferedWriter(writer);
            FileOutputStream fileOutputStream = new FileOutputStream(file);

            for (int i = 0; i < list.size(); i++) {
                if (i % step == 0) {
                    size++;
                    file = new File("D:\\file\\output-" + size + ".txt");
                    fileOutputStream = new FileOutputStream(file);
                }
                fileOutputStream.write((list.get(i) + "\r\n").getBytes());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
